package com.mspbots.core.ticketai.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.mspbots.core.AbstractBaseServiceImpl;
import com.mspbots.core.ticketai.mapper.UtilizationMapper;
import com.mspbots.core.ticketai.model.Utilization;
import com.mspbots.core.ticketai.service.UtilizationService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


@Service
public class UtilizationServiceImpl extends AbstractBaseServiceImpl<UtilizationMapper, Utilization> implements UtilizationService {


    @Override
    public JsonNode listbyweek(Utilization queryParam) {

        List<Utilization> list = baseMapper.listbyweek(queryParam);
        ObjectMapper mapper = new ObjectMapper();

        ArrayNode utiliJsonArr = mapper.createArrayNode();

        Map<Long, ObjectNode> map = new LinkedHashMap<>();
        for (int i = 0; i < list.size(); i++) {
            Long userId = list.get(i).getUserId();
            ObjectNode utiliObj = null;

            if (map.containsKey(userId)) {
                utiliObj = map.get(userId);
            } else {
                utiliObj = mapper.createObjectNode();
                utiliObj.put("tenantId", list.get(i).getTenantId());
                utiliObj.put("userId", userId);
                utiliObj.put("userName", list.get(i).getUserName());
                utiliObj.put("utilYearAvg", list.get(i).getUtilYearAvg());
                utiliObj.put("utilWeekAvg", list.get(i).getUtilWeekAvg());
                utiliObj.put("utilMonthAvg", list.get(i).getUtilMonthAvg());
                utiliObj.put("utilYearAvg", list.get(i).getUtilYearAvg());
                map.put(userId, utiliObj);
            }
            utiliObj.put(list.get(i).getCreateTime().getDayOfWeek().toString().toLowerCase(), list.get(i).getPercent());
        }

        for (Map.Entry<Long, ObjectNode> m : map.entrySet()) {
            utiliJsonArr.add(m.getValue());
        }
        return utiliJsonArr;
    }


    @Override
    public List<Utilization> listcurentyear(Utilization queryParam) {

        QueryWrapper<Utilization> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("tenant_id", queryParam.getTenantId());
        queryWrapper.between("create_time",
                LocalDateTime.of(LocalDateTime.now().getYear(), 1, 1, 0, 0),
                LocalDateTime.now().getDayOfYear());
        List<Utilization> list = baseMapper.listbyweek(queryParam);
        list.stream().forEach(item -> item.setDayOfWeek(item.getCreateTime().getDayOfWeek().toString()));

        return list;
    }

}
